<template>
  <div class="bill-retreat">
    <a-row
      :wrap="true"
      type="flex"
      justify="space-between"
      align="middle"
      class="tab-row"
    >
      <a-tabs v-model:activeKey="activeTab" @change="onTabChange">
        <a-tab-pane
          v-for="item of retreatTabs"
          :key="item.key"
          :tab="item.title"
        >
        </a-tab-pane>
      </a-tabs>
    </a-row>

    <a-form>
      <a-row :wrap="true" class="search-row" :gutter="18">
        <a-col :xl="4" :lg="6" :md="8" :sm="12" :xs="16">
          <a-form-item label="统计月份" :colon="false">
            <a-month-picker
              class="w-100p"
              v-model:value="searchParams.month"
              placeholder="请选择统计月份"
              :format="monthFormat"
              :valueFormat="monthFormat"
              :allowClear="false"
            />
          </a-form-item>
        </a-col>
        <a-col
          :xl="4"
          :lg="6"
          :md="8"
          :sm="12"
          :xs="16"
          v-if="activeTabInfo.search.includes('owner_name')"
        >
          <a-form-item :label="$L('租客')" :colon="false">
            <a-input
              placeholder="请输入"
              v-model:value="searchParams.owner_name"
            />
          </a-form-item>
        </a-col>
        <a-col
          :xl="4"
          :lg="6"
          :md="8"
          :sm="12"
          :xs="16"
          v-if="activeTabInfo.search.includes('proprietor_name')"
        >
          <a-form-item label="业主" :colon="false">
            <a-input
              placeholder="请输入"
              v-model:value="searchParams.proprietor_name"
            />
          </a-form-item>
        </a-col>
        <a-col :xl="4" :lg="6" :md="8" :sm="12" :xs="16">
          <a-form-item label="电话" :colon="false">
            <a-input
              placeholder="请输入电话"
              v-model:value="searchParams.tel"
            />
          </a-form-item>
        </a-col>
        <a-col :xl="4" :lg="6" :md="8" :sm="12" :xs="16">
          <a-form-item :label="$L('楼宇名称')" :colon="false">
            <a-select
              class="w-100p"
              v-model:value="searchParams.build_id"
              placeholder="请选择"
              :options="buildOption"
              allowClear
            ></a-select>
          </a-form-item>
        </a-col>
        <a-col :xl="4" :lg="6" :md="8" :sm="12" :xs="16">
          <a-form-item label="房号" :colon="false">
            <a-input
              placeholder="请输入房号"
              v-model:value="searchParams.room_name"
            />
          </a-form-item>
        </a-col>
        <a-col
          :xl="4"
          :lg="6"
          :md="8"
          :sm="12"
          :xs="16"
          v-if="activeTabInfo.search.includes('retreat_type')"
        >
          <a-form-item label="退租类型" :colon="false">
            <a-select
              class="w-100p"
              v-model:value="searchParams.retreat_type"
              placeholder="请选择"
              :options="retreatOption"
              allowClear
            ></a-select>
          </a-form-item>
        </a-col>
        <a-col
          :xl="4"
          :lg="6"
          :md="8"
          :sm="12"
          :xs="16"
          v-if="activeTabInfo.search.includes('cuser_name')"
        >
          <a-form-item label="登记人" :colon="false">
            <a-input
              placeholder="请输入登记退租人名称"
              v-model:value="searchParams.cuser_name"
            />
          </a-form-item>
        </a-col>
        <a-col
          :xl="4"
          :lg="6"
          :md="8"
          :sm="12"
          :xs="16"
          v-if="activeTabInfo.search.includes('contract_number')"
        >
          <a-form-item label="合同编号" :colon="false">
            <a-input
              placeholder="请输入"
              v-model:value="searchParams.contract_number"
            />
          </a-form-item>
        </a-col>

        <a-col :xl="4" :lg="6" :md="8" :sm="12" :xs="16">
          <a-form-item label="" :colon="false">
            <a-space>
              <a-button type="primary" @click="handleSearch"> 查询 </a-button>
              <a-button @click="reset">重置</a-button>
            </a-space>
          </a-form-item>
        </a-col>
      </a-row>
      <!-- 表格 -->
      <div class="retreat-content">
        <a-table
          sticky
          :dataSource="dataList"
          :columns="activeTabInfo.columns"
          :loading="loading"
          :pagination="pagination"
          @change="handleTableChange"
          rowKey="id"
          :scroll="{ x: 'max-content' }"
          :row-selection="{ onChange: onSelectedRowChange, selectedRowKeys }"
        >
          <template #title>
            <a-row type="flex" justify="end" align="middle">
              <a-button @click="downLoadClick"
                ><template #icon><DownloadOutlined /></template>
                导出报表</a-button
              >
            </a-row>
          </template>

          <template #bodyCell="{ text, record, index, column }">
            <template v-if="column.key === 'owner_name'">
              <span
                :class="record.owner_id ? 'link' : ''"
                @click="onOwnerClick(record.owner_id)"
                >{{ text || "--" }}</span
              >
            </template>
            <template v-if="column.key === 'proprietor_name'">
              <span
                :class="record.proprietor_id ? 'link' : ''"
                @click="onProprietorClick(record.proprietor_id, record)"
                >{{ text || "--" }}</span
              >
            </template>
            <template v-if="column.key === 'contract_number'">
              <span class="link" @click="goContractDetail(record)">{{
                text
              }}</span>
            </template>
            <template v-if="column.key === 'room_number_txt'">
              <span
                v-if="record.build_bind && record.build_bind.room.length > 0"
              >
                <a
                  v-for="room in record.build_bind.room"
                  class="break-a"
                  @click.stop="
                    roomClick(
                      room,
                      record.build_bind.room,
                      record.build_bind.village.id
                    )
                  "
                  >{{ room.layer_name + "-" + room.room_name
                  }}<text v-if="record.build_bind.room.length > 1">, </text>
                </a>
              </span>
              <span v-else>--</span>
            </template>
          </template>
        </a-table>
      </div>
    </a-form>

    <!-- 租客详情 -->
    <OwnerDetailDrawer
      :visible="ownerDetailVisible"
      :id="ownerId"
      @cancel="ownerDetailVisible = false"
    />

    <!-- 房间详情 -->
    <RoomDrawer
      :visible="visibleDetails"
      @cancel="btnCancelDetails"
      :maxRoomNumber="maxRoomNumber"
      :detail="roomDetail"
    />

    <!-- 业主详情 -->
    <CreateProprietor
      :visible="proprietorDetailVisible"
      :id="proprietorId"
      drawerType="view"
      @onClose="proprietorDetailVisible = false"
    />
  </div>
</template>

<script>
import {
  defineComponent,
  reactive,
  toRefs,
  computed,
  ref,
  defineAsyncComponent,
  onActivated,
} from "vue";
import {
  DownloadOutlined,
  InsertRowAboveOutlined,
  SearchOutlined,
} from "@ant-design/icons-vue";
import request from "../../../common/utils/request";
import { useRouter, useRoute } from "vue-router";
import { Form, message, notification } from "ant-design-vue";
const useForm = Form.useForm;
import moment from "moment";
import store from "@/store";
import OwnerDetailDrawer from "@/views/village/OwnerManage/modules/OwnerDetailDrawer.vue";
import CreateProprietor from "@/views/contract/CostContract/modules/CreateProprietor.vue";
import AddNotice from "@/views/bill/AllBills/AddNotice.vue";
import _ from "lodash";
const monthFormat = "YYYY-MM";
import BLCOMMON from "bl-common-vue3";
const RoomDrawer = defineAsyncComponent(() =>
  import("../../../components/village/RoomDrawer.vue")
);

export default defineComponent({
  name: "retreatReportList",
  components: {
    AddNotice,
    OwnerDetailDrawer,
    InsertRowAboveOutlined,
    DownloadOutlined,
    SearchOutlined,
    RoomDrawer,
    CreateProprietor,
  },
  setup() {
    const $router = useRouter();
    const $route = useRoute();

    const state = reactive({
      activeTab: "1",
      activeTabInfo: retreatTabs[0],
      dataList: [],
      loading: false,
      page: 1,
      limit: 10,
      total: 0,
      retreatOption: [], // 退租类型下拉
      buildOption: [], // 楼宇下拉
      ownerId: 0,
      ownerDetailVisible: false,
      proprietorId: 0,
      proprietorDetailVisible: false,
      addNoticeVisible: false,
      addNoticeIds: [],
    });

    const pagination = computed(() => ({
      total: state.total,
      current: state.page,
      pageSize: state.limit,
      showSizeChanger: true,
    }));

    // 搜索参数
    const searchParams = reactive({
      month: moment(), // 统计月份
      owner_name: "", // 租客
      proprietor_name: "", //业主
      tel: "", // 联系电话
      build_id: undefined, //楼宇名称
      room_name: "", // 房号
      retreat_type: undefined, // 退租类型
      cuser_name: "", // 登记人
      contract_number: "", // 合同编号
    });

    // 导出
    const selectedRowKeys = ref([]);
    const onSelectedRowChange = (keys) => {
      if (keys.length > 100) {
        notification.warning({
          message: "警告",
          description: "您最多可勾选100项",
        });
        return;
      }
      selectedRowKeys.value = keys;
    };

    const { resetFields } = useForm(searchParams, {});

    const getDataList = (init = false) => {
      state.loading = true;
      if (init) {
        state.page = 1;
      }
      let params = {
        page: state.page,
        limit: state.limit,
      };
      state.activeTabInfo.search.forEach((key) => {
        if (searchParams[key] || searchParams[key] === 0) {
          params[key] = searchParams[key];
        }
      });
      params.month = moment(params.month).format(monthFormat);
      request
        .post("/org", state.activeTabInfo.requestUrl, { ...params })
        .then((res) => {
          state.dataList = res.list;
          state.total = res.total;
        })
        .finally(() => {
          state.loading = false;
        });
    };

    const onTabChange = () => {
      selectedRowKeys.value = [];
      state.dataList = [];
      state.activeTabInfo = retreatTabs[state.activeTab - 1];
      getDataList(true);
    };

    const reset = () => {
      resetFields();
      getDataList(true);
    };

    const handleTableChange = (pager) => {
      state.page = pager.current;
      state.limit = pager.pageSize;
      getDataList();
    };

    // 导出报表
    let timer = null;
    const iframe = document.createElement("iframe");
    const downLoadClick = () => {
      if (timer) {
        message.warn("操作过于频繁，请稍后尝试");
        return;
      }
      let params = {
        is_export: 1,
        ids: selectedRowKeys.value,
      };
      state.activeTabInfo.search.forEach((key) => {
        if (searchParams[key] || searchParams[key] === 0) {
          params[key] = searchParams[key];
        }
      });
      request
        .post("/org", state.activeTabInfo.requestUrl, { ...params })
        .then((res) => {
          iframe.src = res.result.fileUrl;
          iframe.style.display = "none";
          document.body.appendChild(iframe);
          setTimeout(() => {
            document.body.removeChild(iframe);
          }, 1000);
          message.success("导出成功,请等待文件生成");
          timer = setTimeout(() => {
            timer = null;
          }, 20000);
        });
    };

    /** 查看租客 */
    const onOwnerClick = (id) => {
      if (id) {
        state.ownerId = id;
        state.ownerDetailVisible = true;
      }
    };
    /** 查看业主 */
    const onProprietorClick = (id, record) => {
      if (id) {
        if (record.is_new == 1) {
          state.ownerId = id;
          state.ownerDetailVisible = true;
        } else {
          state.proprietorId = id;
          state.proprietorDetailVisible = true;
        }
      }
    };

    /** 合同详情 */
    const goContractDetail = (record) => {
      $router.push({
        name: "contractDetail",
        query: { id: record.id },
      });
    };

    const handleSearch = () => {
      selectedRowKeys.value = [];
      getDataList(true);
    };

    // 获取最大房源号
    const getMaxRoomNumber = (list) => {
      let max = 0;
      for (let room of list) {
        if (max < Number(room.room_number)) {
          max = Number(room.room_number);
        }
      }
      return max;
    };

    // 房间点击详情
    const maxRoomNumber = ref(0);
    const visibleDetails = ref(false);
    const roomDetail = ref({});

    const roomClick = (room, room_list, village_id) => {
      let roomData = room;
      roomData.village_id = village_id;
      roomDetail.value = roomData;
      maxRoomNumber.value = getMaxRoomNumber(room_list);
      visibleDetails.value = true;
    };

    const btnCancelDetails = () => {
      visibleDetails.value = false;
    };

    // 楼宇筛选
    const getBuildList = () => {
      request
        .get("/org", "/build/villageAndBuildList", {
          checked: 1,
        })
        .then((res) => {
          state.buildOption = [];
          res.villageList.forEach((village) => {
            village.buildList.forEach((build) => {
              state.buildOption.push({
                label: build.build_name,
                value: build.id,
              });
            });
          });
        });
    };

    const init = () => {
      store.dispatch("BillInit").then((data) => {
        state.retreatOption = data?.retreat_type || [];
        getBuildList();
        getDataList(true);
      });
    };

    onActivated(() => {
      selectedRowKeys.value = [];
      init();
    });

    return {
      ...toRefs(state),
      searchParams,
      retreatTabs,
      monthFormat,
      pagination,
      selectedRowKeys,
      visibleDetails,
      maxRoomNumber,
      roomDetail,
      reset,
      getDataList,
      handleTableChange,
      onTabChange,
      downLoadClick,
      onOwnerClick,
      handleSearch,
      onSelectedRowChange,
      roomClick,
      btnCancelDetails,
      onProprietorClick,
      goContractDetail,
    };
  },
});

const columnsFields = [
  {
    title: BLCOMMON.utils.L("租客") + "姓名",
    dataIndex: "owner_name",
    key: "owner_name",
    width: 120,
    fixed: "left",
  },
  {
    title: "业主姓名",
    dataIndex: "proprietor_name",
    key: "proprietor_name",
    width: 120,
    fixed: "left",
  },
  {
    title: "默认联系人",
    dataIndex: "contact_name",
    key: "contact_name",
    width: 120,
  },
  {
    title: "业主联系人",
    dataIndex: "link_name",
    key: "link_name",
    width: 120,
  },
  {
    title: "联系电话",
    dataIndex: "owner_tel",
    key: "owner_tel",
    width: 150,
  },
  {
    title: "业主电话",
    dataIndex: "proprietor_phone",
    key: "proprietor_phone",
    width: 150,
  },
  {
    title: BLCOMMON.utils.L("楼宇名称"),
    dataIndex: "build_name",
    key: "build_name",
    width: 100,
  },
  {
    title: "房号",
    dataIndex: "room_number_txt",
    key: "room_number_txt",
    width: 100,
  },
  {
    title: "应收金额",
    dataIndex: "receive_amount",
    key: "receive_amount",
    customRender: ({ text, record, index }) => {
      return "￥" + text || 0;
    },
    width: 120,
  },
  {
    title: "合同编号",
    dataIndex: "contract_number",
    key: "contract_number",
    width: 220,
  },
  {
    title: "租赁有效期",
    dataIndex: "lease_starttime",
    key: "lease_starttime",
    customRender: ({ text, record, index }) => {
      return record?.lease_starttime + "至" + record?.lease_endtime;
    },
    width: 240,
  },
  {
    title: "租金",
    dataIndex: "rent_amount",
    key: "rent_amount",
    customRender: ({ text, record, index }) => {
      return "￥" + text || 0;
    },
    width: 120,
  },
  {
    title: "押金",
    dataIndex: "bond_amount",
    key: "bond_amount",
    customRender: ({ text, record, index }) => {
      return "￥" + text || 0;
    },
    width: 120,
  },
  {
    title: "欠款金额",
    dataIndex: "overdue_amount",
    key: "overdue_amount",
    customRender: ({ text, record, index }) => {
      return "￥" + text || 0;
    },
    width: 120,
  },
  {
    title: "退租时间",
    dataIndex: "retreat_date",
    key: "retreat_date",
    width: 110,
  },
  {
    title: "退租类型",
    dataIndex: "retreat_type_txt",
    key: "retreat_type_txt",
    width: 100,
  },
  {
    title: "登记人",
    dataIndex: "cuser_name",
    key: "cuser_name",
    width: 100,
  },
  {
    title: "登记时间",
    dataIndex: "created_at",
    key: "created_at",
    width: 180,
  },
  {
    title: "应退金额",
    dataIndex: "cancel_amount",
    key: "cancel_amount",
    customRender: ({ text, record, index }) => {
      return "￥" + text || 0;
    },
    width: 120,
  },
  {
    title: "租赁单价",
    dataIndex: "lease_unit_price",
    key: "lease_unit_price",
    width: 100,
    customRender: ({ text, record, index }) => {
      return text + (record?.lease_unit_price_unit || "");
    },
  },
  {
    title: "物业单价",
    dataIndex: "property_unit_price",
    key: "property_unit_price",
    width: 100,
    customRender: ({ text, record, index }) => {
      return text + (record?.property_unit_price_unit || "");
    },
  },
  {
    title: "保证金",
    dataIndex: "bond_amount",
    key: "earnest_money",
    customRender: ({ text, record, index }) => {
      return "￥" + text || 0;
    },
    width: 100,
  },
  {
    title: "计租方式",
    dataIndex: "lease_mode_txt",
    key: "lease_mode_txt",
    width: 120,
  },
];
const ownerDefault = [
  "owner_name",
  "contact_name",
  "owner_tel",
  "build_name",
  "room_number_txt",
];

const keyOneColumns = columnsFields.filter((item) =>
  ownerDefault
    .concat([
      "contract_number",
      "lease_starttime",
      "rent_amount",
      "bond_amount",
      "overdue_amount",
    ])
    .includes(item.key)
);
const keyTwoColumns = columnsFields.filter((item) =>
  ownerDefault
    .concat([
      "receive_amount",
      "contract_number",
      "lease_starttime",
      "retreat_date",
      "retreat_type_txt",
      "cuser_name",
      "created_at",
    ])
    .includes(item.key)
);

const proprietorDefault = [
  "proprietor_name",
  "link_name",
  "proprietor_phone",
  "build_name",
  "room_number_txt",
  "contract_number",
  "lease_starttime",
];
const keyThreeColumns = columnsFields.filter((item) =>
  proprietorDefault
    .concat([
      "lease_unit_price",
      "property_unit_price",
      "earnest_money",
      "lease_mode_txt",
    ])
    .includes(item.key)
);
const keyFourColumns = columnsFields.filter((item) =>
  proprietorDefault
    .concat([
      "cancel_amount",
      "lease_unit_price",
      "property_unit_price",
      "earnest_money",
      "lease_mode_txt",
    ])
    .includes(item.key)
);

const retreatTabs = [
  {
    key: "1",
    title: BLCOMMON.utils.L("租客") + "合同到期",
    search: ["month", "owner_name", "tel", "build_id", "room_name"],
    requestUrl: "/report/ownerContract/expireList",
    columns: _.cloneDeep(keyOneColumns).map((v) => {
      v.key = "one_" + v.key;
      return v;
    }),
  },
  {
    key: "2",
    title: BLCOMMON.utils.L("租客") + "已退房",
    search: [
      "month",
      "owner_name",
      "tel",
      "build_id",
      "room_name",
      "retreat_type",
      "cuser_name",
      "contract_number",
    ],
    requestUrl: "/report/ownerContract/retreatList",
    columns: _.cloneDeep(keyTwoColumns).map((v) => {
      v.key = "two_" + v.key;
      return v;
    }),
  },
  {
    key: "3",
    title: "业主合同到期",
    search: ["month", "proprietor_name", "tel", "build_id", "room_name"],
    requestUrl: "/report/proprietor/expireList",
    columns: _.cloneDeep(keyThreeColumns).map((v) => {
      v.key = "three_" + v.key;
      return v;
    }),
  },
  {
    key: "4",
    title: "业主已退房",
    search: ["month", "proprietor_name", "tel", "build_id", "room_name"],
    requestUrl: "/report/proprietor/retreatList",
    columns: _.cloneDeep(keyFourColumns).map((v) => {
      v.key = "four_" + v.key;
      return v;
    }),
  },
];
</script>

<style lang="less" scoped>
.bill-retreat {
  padding: 10px;
  .tab-row {
    background: #fff;
    padding: 0 10px;
  }
  .search-row {
    margin: 10px 0 0 0 !important;
    background: #fff;
    padding: 24px 10px 0 10px;
  }
  :deep(.ant-tabs-bar) {
    margin: 0;
  }

  .retreat-content {
    margin-top: 1px;
    background: #fff;
    padding: 0 10px;
  }
}
.break-a {
  word-break: break-all;
  display: block;
}
</style>
